// sendCode.js
const nodemailer = require('nodemailer');

/**
 * SMTP 邮件发送器配置（通用）
 */
const transporter = nodemailer.createTransport({
    host: 'email.whu.edu.cn',        // 👉 修改为你的邮箱 SMTP 地址
    port: 465,                  // 👉 通常是 465（SSL）或 587（TLS）
    secure: true,               // 👉 如果用 465 则为 true；587 则为 false
    auth: {
        user: 'quantumcloud@whu.edu.cn',      // 👉 改成你自己的邮箱
        pass: 'Tipsi@Wuhan2023!'// 👉 不是邮箱密码！是授权码！
    },
    pool: true, // ✅ 开启连接池
});



/**
 * 向邮箱发送验证码
 * @param {string} email 接收者邮箱
 * @param {string} code 验证码
 */
async function sendCode(email, code) {
    const mailOptions = {
        from: '"TBPLAS" <quantumcloud@whu.edu.cn>', // 发件人邮箱
        to: email,                      // 收件人
        subject: 'Your Verification Code',
        html: `
      <div style="font-family: Arial, sans-serif; max-width: 480px; margin: 0 auto; padding: 24px; background-color: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; font-size: 16px; color: #333;">
  <h2 style="color: #007bff; font-weight: 600; font-size: 20px;">TBPLAS Verification</h2>

  <p style="margin-top: 20px;">Hello,</p>

  <p>Your verification code is:</p>

  <div style="margin: 16px 0; padding: 12px 24px; background-color: #eef6ff; border: 1px dashed #007bff; border-radius: 6px; display: inline-block;">
    <span style="font-size: 28px; font-weight: bold; color: #007bff;">${code}</span>
  </div>

  <p>This code is valid for <strong>10 minute</strong>. Please do not share it with anyone.</p>

  <p style="margin-top: 32px; font-size: 14px; color: #999;">— TBPLAS System</p>
</div>

    `
    };

    return transporter.sendMail(mailOptions);
}


/**
 * 群发邮件
 * @param {string[]} emails 收件人邮箱数组
 * @param {string} subject 邮件主题
 * @param {string} html 邮件HTML正文
 * @returns {Promise<{successList:string[], failedList:{email:string,error:Error}[]}>}
 */
async function sendMassEmail(emails, subject, html) {
    const successList = [];
    const failedList = [];

    for (const email of emails) {
        const mailOptions = {
            from: '"TBPLAS" <quantumcloud@whu.edu.cn>', // 发件人
            to: email,
            subject,
            html,
        };

        try {
            await transporter.sendMail(mailOptions);
            successList.push(email);
        } catch (error) {
            failedList.push({ email, error });
        }
    }

    return { successList, failedList };
}

module.exports = { sendCode, sendMassEmail };
